# -*- coding: utf-8 -*-

import remi.gui
from remi.gui import *
import remi.gui as gui
from threading import Timer


# https://python-snap7.readthedocs.io/en/latest/util.html
# https://github.com/gijzelaerr/python-snap7/blob/master/example/boolean.py

class TimerWidget(Image):
    icon = ""
    
    stop = True #the stop flag for the timer, when True the timer stops

    @property
    @gui.editor_attribute_decorator('WidgetSpecific','The Interval in milliseconds', int, {'default':0, 'min':0, 'max':65535, 'step':1})
    def interval_milliseconds(self): return self.__interval_milliseconds
    @interval_milliseconds.setter
    def interval_milliseconds(self, v): self.__interval_milliseconds = v

    @property
    @gui.editor_attribute_decorator('WidgetSpecific','The autostart flag, if True the timer starts at creation', bool, {})
    def autostart(self): return self.__autostart
    @autostart.setter
    def autostart(self, v): 
        self.__autostart = v
        if self.__autostart:
            self.start()
        else:
            self.stop = True

    def __init__(self, interval_milliseconds=1000, autostart=True, *args, **kwargs):
        self.__interval_milliseconds = interval_milliseconds
        self.__autostart = autostart
        super(TimerWidget, self).__init__(self.icon, *args, **kwargs)
        self.style.update({'position':'absolute','left':'10px','top':'10px','width':'46px','height':'46px'})
        self.stop = False
        if autostart: 
            self.onelapsed()

    @gui.decorate_set_on_listener("(self, emitter)")
    @gui.decorate_event
    def onelapsed(self, *args):
        if not self.stop:
            Timer(self.interval_milliseconds/1000.0, self.onelapsed).start()
        self.stop = False
        return ()

    def stop(self, *args):
        self.stop = True

    def start(self, *args):
        if self.stop:
            self.onelapsed()